<template>
	<view>
		<up-popup ref="popupLogin" :show="popupLoginShow" :closeOnClickOverlay="false" mode="bottom" @close="popupLoginShow = false" closeable
			:round="'30rpx'">
			
			<view class="login-box">
				<view class="login-box-title">
					<text class="slogan">{{ title }}</text>
					<text class="slogan2">{{ slogan }}</text>
				</view>


				<view class="login-userinfo">
				<!-- 手机号绑定 -->
				<view v-if="!userinfo.phone" class="login-btn">
						<!-- <view class="bind-type-switch" style="text-align:center;">
							<button class="switch-btn" @click="bindType = bindType === 'wechat' ? 'sms' : 'wechat'">
								{{ bindType === 'wechat' ? '短信验证码绑定' : '切换微信一键绑定' }}
							</button>
						</view> -->
						<view v-if="bindType === 'wechat'">
							<button class="wxlogin btndefault" open-type="getPhoneNumber" @getphonenumber="loginPhone">
								<view class="btn-content">
									<text>{{ currentBtnText }}</text>
									<text class="recommend-tag">推荐</text>
								</view>
							</button>
						</view>
						<view v-else style="width:100%;">
							<input type="text" v-model="smsPhone" placeholder="请输入手机号" maxlength="11" style="width:100%;margin-bottom:16rpx;padding:20rpx 16rpx;border-radius:8rpx;border:1rpx solid #eee;" />
							<view class="sms-row" style="display:flex;align-items:center;margin-bottom:16rpx;">
								<input type="text" v-model="smsCode" placeholder="验证码" maxlength="6" style="flex:1;padding:20rpx 16rpx;border-radius:8rpx;border:1rpx solid #eee;" />
								<button :disabled="smsTimer > 0" @click="getSmsCode" style="margin-left:16rpx;min-width:140rpx;">{{ smsBtnText }}</button>
							</view>
							<button class="wxlogin btndefault" :disabled="!smsPhone || !smsCode" @click="loginPhoneBySms">
								绑定手机号码
							</button>
						</view>
						<!-- 跳过按钮 -->
						<button class="skip-btn btndefault" @click="skipCurrentStep">
							跳过此步骤
						</button>
					</view>
				</view>
				<view class="agreement-box" :class="{ 'shake-animation': isShaking }">
				<view class="custom-checkbox" @click="toggleAgreement">
					<view class="checkbox-icon" :class="{ 'checked': checkboxValue.length > 0 }">
						<text v-if="checkboxValue.length > 0" class="iconfont icon-zhengque1" style="color: #3b93ee;"></text>
					</view>
					<view class="agreement-txt">
						<text>我已阅读并同意</text>
						<navigator class="agreement" url="../userInfo/agreement">《用户协议》、</navigator>
						<navigator class="agreement" url="../userInfo/privacy">《隐私政策》</navigator>
					</view>
				</view>
			</view>
			</view>
		</up-popup>
	</view>
</template>

<script>
import {
	getWxPhone,
	getWxLogin,
	putUserUpdate,
	getDetail,
	getPhoneCode,
	authCodePhone
} from '@/http/user.js'


export default {
	name: "loginPopup",
	props: {
		title: {
			type: String,
			default: '绑定手机号码!'
		},
		slogan: {
			type: String,
			default: '-绑定手机获得更多学习功能-!'
		},
		btnText: {
			type: String,
			default: '微信手机号登录'
		},
	},
	data() {
		return {
			userinfo: {
				phone: '',
				wechatOpenid: '',
				sessionKey: ''
			},
			checkboxValue: [],
			isShaking: false,
			bindType: 'wechat', // 'wechat' 或 'sms'
			smsPhone: '', // 短信方式输入的手机号
			smsCode: '', // 短信验证码
			smsTimer: 0, // 倒计时
			smsBtnText: '获取验证码',
			popupLoginShow: false,
			token:'',
			// 微信登录缓存
			wxLoginCache: null, // 缓存的微信登录信息
			wxLoginPromise: null // 正在进行的微信登录Promise
		};
	},
	computed: {
		// 按钮文本
		currentBtnText() {
			return '微信一键绑定'
		}
	},

	onLoad() {

	},
	methods: {
		someMethod() {
			console.log('someMethod is called');
		},
		popChange(val) {
			// if (!val.show && this.token == '') {
			// 	this.$store.dispatch('cancelLogin')
			// 	uni.showToast({
			// 		title: '取消注册',
			// 		icon: 'error'
			// 	});
			// }
			// this.$store.dispatch('handleLoginPop', val.show)
		},
		async show(val) {
			// this.$refs.popupLogin.open()
			this.popupLoginShow = true
			this.token = val.token
			console.log(val, 'wxLoginData show');
			this.userinfo = val || {
				phone: '',
				wechatOpenid: '',
				sessionKey: ''
			}
			console.log(this.userinfo, 'userinfo 142');

			// 如果传入的userinfo有微信信息，检查session是否有效
			if (this.userinfo.wechatOpenid && this.userinfo.sessionKey) {
				console.log('检查传入的微信session是否有效')
				const sessionValid = await this.checkSession()
				if (sessionValid) {
					console.log('传入的微信session有效，可直接使用')
					// session有效，可以直接使用传入的微信信息
				} else {
					console.log('传入的微信session已过期，需要重新获取')
					// session过期，清除微信信息，后续需要重新获取
					this.userinfo.wechatOpenid = ''
					this.userinfo.sessionKey = ''
				}
			}
		},

	
		// 完成登录
		async completeLogin() {
			console.log('17:16:13 🚀 ~ file: loginPopup.vue:328 ~ completeLogin ~ ', this.userinfo)
			try {
				uni.showLoading({
					title: '正在完成登录...',
					mask: true
				})
				// 将token存入storage
				uni.setStorageSync('token', this.token)
				// 获取最新的用户信息
				const detailRes = await getDetail()
				console.log(detailRes, 'detailRes');

				uni.setStorageSync('userinfo', detailRes.data)
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				})

				this.$emit('success')
				this.close()

			} catch (error) {
				console.log(error, 'error');
				if(error.data.message.includes('绑定')){
					uni.showModal({
						title: '注册失败',
						content: error.data.message,
						confirmText: '联系客服',
						success: ({ confirm, cancel }) => {
							if (confirm) {
								uni.makePhoneCall({
								phoneNumber: '15362749188',
								success: () => {
									console.log('拨打电话成功')
								},
								fail: (err) => {
									console.log('拨打电话失败', err)
								}
								})
							}
						}
					})
					return
				}
				uni.showToast({
					title: error.data.message || '登录失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
	
		close() {
			// this.$refs.popupLogin.close()
			this.popupLoginShow = false
		},

		// 清除微信登录缓存
		clearWxLoginCache() {
			console.log('清除微信登录缓存')
			this.wxLoginCache = null
			this.wxLoginPromise = null
		},


		// 检查session是否有效
		checkSession() {
			return new Promise((resolve, reject) => {
				uni.checkSession({
					success: () => {
						console.log('session有效')
						resolve(true)
					},
					fail: () => {
						console.log('session已过期')
						resolve(false)
					}
				})
			})
		},

		// 无感微信登录（智能判断是否需要重新获取）
		async silentWxLogin() {
			try {
				// 情况1：如果userinfo中已有有效的微信信息，直接使用
				if (this.userinfo.wechatOpenid && this.userinfo.sessionKey) {
					console.log('使用userinfo中的微信信息')
					return {
						data: {
							wechatOpenid: this.userinfo.wechatOpenid,
							sessionKey: this.userinfo.sessionKey
						}
					}
				}

				// 情况2：没有微信信息或已过期，需要重新获取
				console.log('userinfo中没有微信信息，需要重新获取')

				// 如果有缓存的登录信息，先检查session是否有效
				// if (this.wxLoginCache) {
				// 	const sessionValid = await this.checkSession()
				// 	if (sessionValid) {
				// 		console.log('使用缓存的微信登录信息')
				// 		return this.wxLoginCache
				// 	} else {
				// 		console.log('缓存的session已过期，清除缓存')
				// 		this.wxLoginCache = null
				// 	}
				// }

				// 如果正在进行微信登录，直接返回该Promise
				// if (this.wxLoginPromise) {
				// 	console.log('正在进行微信登录，等待结果')
				// 	return await this.wxLoginPromise
				// }

				// 开始新的微信登录流程
				console.log('开始新的微信登录流程')
				this.wxLoginPromise = this.performWxLogin()
				
				try {
					const result = await this.wxLoginPromise
					console.log(result, 'result299');
					
					this.wxLoginCache = result // 缓存登录结果
					// 同时更新userinfo中的微信信息
					if (result.data) {
						console.log(result.data, 'result.data304');
						this.userinfo.wechatOpenid = result.data.wechatOpenid
						this.userinfo.sessionKey = result.data.sessionKey
						this.userinfo.token = result.data.token
					}
					return result
				} finally {
					this.wxLoginPromise = null // 清除Promise引用
				}
			} catch (error) {
				console.error('无感登录失败:', error)
				this.wxLoginPromise = null // 清除Promise引用
				throw error
			}
		},

		// 执行微信登录
		async performWxLogin() {
			const loginRes = await this.getWxLoginCode()
			console.log(loginRes, '微信登录code获取成功');
			const wxRes = await getWxLogin({ code: loginRes.code, uid: this.userinfo.id })
			console.log(wxRes, '微信登录结果324')
			return wxRes
		},

		// 获取微信登录code
		getWxLoginCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: reject
				})
			})
		},

		// 微信手机号登录
		async loginPhone(val) {
			try {
				uni.showLoading({
					title: '绑定手机号...',
					mask: true
				})
				console.log(this.userinfo, 'this.userinfo347');
				let wxRes = await this.silentWxLogin()
				console.log(wxRes, '微信登录结果349');
				// console.log(wxRes, '微信登录结果347');
				// 检查是否已经是注册用户
				// if(wxRes.data && wxRes.data.username){
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '微信账号：' + wxRes.data.username + '已注册，请直接登录',
				// 		showCancel: false,
				// 		confirmText: '确认登录',
				// 		success: ({ confirm, cancel }) => {
				// 			if (confirm) {
				// 				uni.setStorageSync('token', wxRes.data.token)
				// 				uni.setStorageSync('userinfo', wxRes.data)
				// 				this.$emit('success')
				// 				this.close()
				// 			}
				// 		}
				// 	})
				// 	return
				// }
				
				// silentWxLogin已经处理了微信信息的设置，这里不需要重复设置
				
				console.log(this.userinfo, 'this.userinfo600');

				const paramsPhone = {
					code: val.detail.code,
					encryptedData: val.detail.encryptedData,
					iv: val.detail.iv,
					sessionKey: wxRes.data.sessionKey,
					uid: this.userinfo.id
				}
				let phoneRes = await getWxPhone(paramsPhone)
				uni.setStorageSync('token', this.userinfo.token)
				// 将手机号码存入注册信息
				this.userinfo.phone = phoneRes.data
				console.log(this.userinfo, 'this.userinfo615');

				// 进入下一步
				this.completeLogin()

			} catch (err) {
				uni.showToast({
					title: '绑定手机号失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		toggleAgreement() {
			this.checkboxValue = this.checkboxValue.length > 0 ? [] : [1]
		},
		async getSmsCode() {
			if (!/^1\d{10}$/.test(this.smsPhone)) {
				uni.showToast({ title: '请输入正确手机号', icon: 'none' })
				return
			}
			try {
				await getPhoneCode({ phone: this.smsPhone })
				this.smsTimer = 60
				this.smsBtnText = '60s'
				let timer = setInterval(() => {
					this.smsTimer--
					this.smsBtnText = this.smsTimer > 0 ? `${this.smsTimer}s` : '获取验证码'
					if (this.smsTimer <= 0) clearInterval(timer)
				}, 1000)
				uni.showToast({ title: '验证码已发送', icon: 'success' })
			} catch (e) {
				uni.showToast({ title: e.message || '发送失败', icon: 'none' })
			}
		},
		async loginPhoneBySms() {
			if (!/^1\d{10}$/.test(this.smsPhone)) {
				uni.showToast({ title: '请输入正确手机号', icon: 'none' })
				return
			}
			if (!this.smsCode) {
				uni.showToast({ title: '请输入验证码', icon: 'none' })
				return
			}
			try {
				await authCodePhone({ phone: this.smsPhone, authCode: this.smsCode })
				this.userinfo.phone = this.smsPhone
				let wxRes = await this.silentWxLogin()
				// this.userinfo.token = wxRes.data.token
				console.log(wxRes, 'wxRes');
				
				this.completeLogin()
			} catch (e) {
				uni.showToast({ title: e.message || '验证码错误', icon: 'none' })
			}
		},
		// 跳过当前步骤
		async skipCurrentStep() {
			uni.showModal({
				title: '确认跳过',
				content: '确定要跳过手机号绑定吗？',
				confirmText: '确定跳过',
				cancelText: '取消',
				success: async ({ confirm }) => {
					if (confirm) {
						// 跳过手机号绑定，直接完成登录
						this.userinfo.phone = 'skipped'
						await this.completeLogin()
					}
				}
			})
		},
	}
}
</script>

<style lang="less" scoped>

.login-box {
	background: linear-gradient(180deg, #B4CDF8, rgba(239,243,250,0));
	background-size: 100% 345rpx;
	background-repeat: no-repeat;
	background-color: #F7F6F9;
	border-radius: 30rpx 30rpx 0rpx 0rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0 120rpx 0;
	position: relative;

	.login-box-title {
		text-align: center;
		margin-bottom: 40rpx;

		text {
			display: block;
		}

		.slogan {
			font-weight: 700;
			font-size: 46rpx;
			color: #2C2821;
			margin-bottom: 16rpx;
		}

		.slogan2 {
			font-weight: 400;
			font-size: 30rpx;
			color: #4460E5;
		}
	}


	.login-userinfo {
		margin-top: 40rpx;
		width: 100%;
		padding: 0 60rpx;
		box-sizing: border-box;

		.login-btn {
			margin-top: 40rpx;

			.btndefault {
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
				border-radius: 50rpx;
				font-weight: 700;
				font-size: 32rpx;
				color: #FFFFFF;
				margin-bottom: 30rpx;
				background: #04C051;
				transition: all 0.3s ease;
				box-shadow: 0 6rpx 20rpx rgba(4, 192, 81, 0.2);

				&:active {
					transform: scale(0.98);
					box-shadow: 0 4rpx 12rpx rgba(4, 192, 81, 0.15);
				}

				&.wxlogin {
					background: linear-gradient(135deg, #04C051, #03A745);
				}

				&[disabled] {
					background: #ccc;
					box-shadow: none;
				}
			}

			.skip-btn {
				background: #f5f5f5 !important;
				color: #cecece !important;
				height: 60rpx !important;
				font-size: 24rpx !important;
				line-height: 60rpx !important;
				border: 1rpx solid #b3b3b3 !important;
				margin-top: 20rpx;
				font-weight: 100 !important;
				box-shadow: none !important;

				&:active {
					background: #e8e8e8 !important;
					transform: scale(0.98);
				}
			}
		}

	}

	.agreement-box {
	position: fixed;
	left: 50%;
	bottom: 40rpx;
	transform: translateX(-50%);
	font-weight: 600;
	font-size: 24rpx;
	color: #A5A5A5;
	text-align: center;
	width: 100%;
	padding: 0 30rpx;
	box-sizing: border-box;

	.custom-checkbox {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		cursor: pointer;

		.checkbox-icon {
			width: 36rpx;
			height: 36rpx;
			border: 2rpx solid #A5A5A5;
			border-radius: 50%;
			margin-right: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s;

			&.checked {
				background: #fff;
				border-color: #4460E5;
			}

			.icon-check {
				color: #fff;
				font-size: 24rpx;
			}
		}

		.agreement-txt {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.agreement {
			color: #4460E5;
		}
	}
}

}

@keyframes shake {

	0%,
	100% {
		transform: translateX(0);
	}

	25% {
		transform: translateX(-8rpx);
	}

	75% {
		transform: translateX(8rpx);
	}
}

.shake-element {
	animation: shake 0.5s ease-in-out;
}


.switch-btn {
	background: #fff;
	color: #4460E5;
	border: 2rpx solid #4460E5;
	border-radius: 40rpx;
	font-size: 26rpx;
	margin-bottom: 30rpx;
	transition: background 0.2s, color 0.2s;
	box-shadow: 0 2rpx 8rpx rgba(252,56,38,0.08);
}
.switch-btn:active {
	background: #4460E5;
	color: #fff;
}

.btn-content {
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	
	.recommend-tag {
		position: relative;
		margin-left: 8rpx;
		background: #4460E5;
		color: #fff;
		height: 40rpx;
		line-height: 40rpx;
		padding: 2rpx 8rpx;
		border-radius: 12rpx;
		font-size: 20rpx;
		font-weight: normal;
		transform: scale(0.8);
		transform-origin: left center;
		box-shadow: 0 2rpx 4rpx rgba(253, 53, 35, 0.2);
	}
}
</style>